package com.zzy.demo.security.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzy.demo.common.dto.CodeMsg;
import com.zzy.demo.common.dto.Result;
import com.zzy.demo.common.enums.LoginTypeEnum;
import com.zzy.demo.config.properties.SecurityProperties;


/**
 * 登录失败处理
 * @author 郭凯歌
 *
 */
@Component("myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	SecurityProperties securityProperties;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		
		logger.error("登陆失败");

		if (LoginTypeEnum.JSON.equals(securityProperties.getBrowser().getLoginType())) {
			
			String result = objectMapper.writeValueAsString(exception.getMessage());
			
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.setContentType("application/json;charset=UTF-8");
			response.getOutputStream()
					.write(objectMapper.writeValueAsString(Result.error(new CodeMsg(-1, result))).getBytes());
			
		} else {
			request.setAttribute("errorMsg", exception.getMessage());
			request.getRequestDispatcher("/login").forward(request, response);
			//super.onAuthenticationFailure(httpServletRequest, httpServletResponse, exception);
		}
	}
}
